<template>
    <div>
        <el-tabs type="border-card">
            <el-tab-pane label="子账户" :name="0">
                <el-form :inline="true" :model="queryForm">

                        <el-form-item>
                        <el-button type="primary" @click="pingcangs">
                            批量强平
                        </el-button>
                        </el-form-item>
                </el-form>
                <div>
                 
                    <el-table
                        :data="tableData"
                        :height="getH"
                        class="table"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >   
                        
                         <el-table-column
                        width="55">
                            <template
                                slot="header"
                                #header="scope"
                            >
                                <el-checkbox v-model="checkedAll" @change="handleSelectionChange"></el-checkbox>
                            </template>

                            <template #default="{ row }">
                                <div>
                                   <el-checkbox v-model="row.checked" ></el-checkbox>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column  prop="username" label="账号" show-overflow-tooltip  width="120"></el-table-column>
                        <el-table-column  prop="nickname" label="昵称" show-overflow-tooltip  width="120"></el-table-column>
                        <el-table-column  prop="positionnum" label="持仓编号" width="80" show-overflow-tooltip>
                            
                        </el-table-column>
                        <el-table-column  prop="volume" label="持仓数" width="60" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column  prop="contract" label="合约" align="center"  width="120" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div style="text-align:center">
                                   {{ row.contract + '-' + row.codename }}
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column  prop="cmd" label="下单类型" width="80" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div>
                                   {{ getType(row)}}
                                </div>
                            </template>
                        </el-table-column>
                        
                        <el-table-column  prop="cmd" label="方向" width="60" show-overflow-tooltip align="center">
                            <template #default="{ row }">
                                <div>
                                   {{ row.risefall == 'rise' ? '买':'卖' }}
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column  prop="volume" label="下单数量" align="center" width="80" show-overflow-tooltip></el-table-column>
                        <el-table-column  prop="playprice" label="持仓价" width="80" align="center" show-overflow-tooltip></el-table-column>
                         <el-table-column  prop="newPrice" label="最新价" width="80" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column min-width="150" prop="yingkui" label="持仓盈亏" width="120" align="center" show-overflow-tooltip>
                                <template #default="{ row }">
                                    <el-tag type="danger" v-if="row.yk >= 0">{{ row.yk }}</el-tag>
                                    <el-tag type="success" v-else>{{ row.yk }}</el-tag>
                                </template>
                        </el-table-column>
                        <el-table-column  prop="margin" label="保证金" width="120" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column  prop="fee" label="手续费" width="120" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column  prop="rate" label="币种" width="60" align="center" show-overflow-tooltip></el-table-column>
                        <el-table-column  prop="rate" label="成交时间" show-overflow-tooltip>
                            <template #default="{ row }">
                                <div>
                                    {{ dayjs.unix(row.updatetime).format('YYYY-MM-DD HH:mm:ss') }}
                                </div>
                                </template>
                        </el-table-column>

                        <el-table-column
                            show-overflow-tooltip
                            fixed="right"
                            align="center"
                            label="操作"
                            width="70"
                        >
                            <template #default="{ row }">
                            <el-button type="text" @click="pingcang(row)">
                                强制平仓
                            </el-button>
                            </template>
                        </el-table-column>

                </el-table>
                </div>
                
            </el-tab-pane>
            <el-tab-pane label="主账户" :name="1">
                <div class="container">
                    <el-table
                        :data="tableData"
                        :height="getH"
                        class="table"
                        ref="multipleTable"
                        header-cell-class-name="table-header"
                    >
                        <el-table-column  prop="name" label="用户"></el-table-column>
                        <el-table-column width="100" label="账户  （可复制）" prop="uname">
                            
                        </el-table-column>
                        <el-table-column width="100" prop="quanyi"  label="持仓编号（可复制）" align="center">
                           
                        </el-table-column>
                        <el-table-column  prop="qichu" label="合约"></el-table-column>
                        <el-table-column  label="方向" align="center" prop="fudong">
                        </el-table-column>

                        <el-table-column  prop="pingcang" label="持仓价"></el-table-column>

                        <el-table-column  prop="risk" label="持仓量"></el-table-column>

                        <el-table-column  prop="baozhengjin" label="可平"></el-table-column>

                        <el-table-column  prop="dongjiebaozhengjin" label="计算价格"></el-table-column>

                        <el-table-column  prop="yk" label="持仓盈亏"></el-table-column>

                        <el-table-column  prop="chicanglinag" label="币种"></el-table-column>

                        <el-table-column  prop="chicanglinag" label="成交时间"></el-table-column>
                    </el-table>
                </div>
            </el-tab-pane>
            
        </el-tabs>

        <div style="height: 30px;
            width: 100%;
            background: rgb(255, 255, 255);
            margin-top: 10px;box-shadow:10px 0 10px rgba(0,0,0,.1)" class="cccc view flex-row align-center">
                <div style="margin-right:15px;font-size: 12px;margin-left:30px;">共{{ total }}条</div>
                <div style="margin-right:15px;font-size: 12px;">持仓量： {{ chicangnum }}</div>
                <div style="margin-right:15px;font-size: 12px;">可平：{{ pingcangnum }}</div>
                <div style="font-size: 12px;">持仓盈亏： <span :style="chicangyk> 0 ?'color: red;':'color: green;'">{{ chicangyk }}</span></div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="form.address"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { chicang,sub,contactlist, getdeviceid, qingping } from "../api/index";
import dayjs from 'dayjs'
import { mapState } from 'vuex';
const zlib = require('zlib');


const unzipBuff = (buffer, cb) => {
	zlib.unzip(buffer, (err, buffer) => {
		if (!err) {
			cb && cb(buffer.toString())
		}
	});
} 
export default {
    computed: mapState({
        ticket: state => state.ticket /*,, 推送数据 */,
        userInfo: state => state.userInfo,
        zijinSet: state => state.zijinSet,
        getH() {
            return window.innerHeight - 300
        },
    }),
    data() {
        return {
            $socket: null,
            timer: null,
            dayjs: dayjs,
            chicangnum: 0,
            pingcangnum: 0,
            chicangyk: 0,
            query: {
                address: "",
                name: "",
                pageIndex: 1,
                pageSize: 10
            },
            heartBean: null,
            checkedAll: false,
            tableData: [],
            multipleSelection: [],
            selectData: [],
            delList: [],
            editVisible: false,
            total: 0,
            form: {},
            idx: -1,
            id: -1
        };
    },
    created() {
        this.init()
        this.timer = setInterval(() => {
            this.getData();
        }, 10000);
        this.getData();
    },
    
    watch: { 
        ticket:{
    　　　　handler: function(val) {
            this.tableData = this.tableData.map( item => {
                let currentItem = val.find( data => {
                    return  data.M + data.S + data.C == item.contract
                })
                if (currentItem) {
                    if (item.risefall == 'rise') {
                        item.newPrice = currentItem.B1
                    } else {
                        item.newPrice = currentItem.S1
                    }
                    
                    item = {...item, ...currentItem}
                } 
                let yk = this.getYK(item)
                item.yk = yk
                return item
                })
           this.multipleSelection =  this.tableData.filter( item => item.checked).map(item => item)   
    　　　},
        immediate: true,
    　　　 deep:true
　　    },
    },
    beforeRouteLeave (to, from, next) {
        if (this.heartBean) {
            clearInterval(this.heartBean)
        }
        if (this.timer) {
            clearInterval(this.timer)
        }
        // 导航离开该组件的对应路由时调用
        this.$socket && this.$socket.close()  //销毁时执行的代码
        next()    //允许跳转页面
    },
    methods: {
        getYK(item) {
            let dc = 0
            if (!item || !item.N) {
                return dc
            }
            let p = 0
            if (item.risefall == 'rise') {
                if (item.N.indexOf('日元') > -1) {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(7)
                } else if (item.N.indexOf('欧元') > -1) {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(5)
                } else {
                    dc = isNaN((item.newPrice - item.playprice)) ? 0:(item.newPrice - item.playprice).toFixed(3)
                }
                
                if (dc == 0) {
                    p = 0
                
                    return p
                }
                
                if (item.N.indexOf('日元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
                
                    return  p
                } else if (item.N.indexOf('欧元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
                
                    return  p
                } else {
                    p =  (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
                
                    return p
                }
            } else {
                if (item.N.indexOf('日元') > -1) {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(7)
                } else if (item.N.indexOf('欧元') > -1) {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(5)
                } else {
                    dc = isNaN((item.playprice - item.newPrice)) ? 0:(item.playprice - item.newPrice).toFixed(3)
                }
                
                if (dc == 0) {
                    p = 0
                
                    return p
                }
                if (item.N.indexOf('日元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
                
                    return  p
                } else if (item.N.indexOf('欧元') > -1) {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
                
                    return  p
                } else {
                    p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
                
                    return  p
                }
            }
            
            },
        conn: function(conn) {
            let connection =  'ws://120.79.84.58:9501/id/'
            connection += conn
            if (!this.$socket) {
                if (typeof WebSocket == 'undefined') {
                    console.error('当前浏览器不支持websocket');
                    return false;
                }

                if (!connection) {
                    console.error('[mysocket] cannot locate connection');
                    return false;
                }
                this.$socket = new WebSocket(connection);
                this.$socket.onopen = (e) => {
                    this.onopen()
                };
                this.$socket.onmessage = (e) => {
                    var buffer = new Buffer(e.data, 'base64');
                    unzipBuff(buffer, (res) => {
                        this.onmessage(JSON.parse(res))
                    })
                    
                };

                this.$socket.onclose = (e) => {
                    this.onclose()
                };
            } else {
                this.$socket.close()

            }
        },
        onopen() {
            this.loadSymbol()
            this.sendHeartBean()
        },
        onmessage(data) {
            if (data.Cmd == 'all') {
                this.$store.commit('setTicket', data.data.filter( item => !!item).map( item => item));
            }
        },
        onclose() {
            this.$socket = null
            clearInterval(this.heartBean)
            this.heartBean = null
        },
        pingcangs(row) {
            if (this.multipleSelection.length == 0) {
                this.$message.error('请选择一条数据')
                    return 
            }
            this.$confirm('确定强制平仓吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }).then(() => {
                qingping({wtnum: this.multipleSelection.map(item => item.wtnum).join(',')}).then(res => {
                        this.$message.success(res.msg)
                        this.getData()
                    }).catch(ret => {
                        this.$message.error(ret.msg)
                    })
            })
        },
        pingcang(row) {
            this.$confirm('确定强制平仓吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                }).then(() => {
                qingping({wtnum: row.wtnum}).then(res => {
                        this.$message.success(res.msg)
                        this.getData()
                    }).catch(ret => {
                        this.$message.error(ret.msg)
                    })
            })
        },
        getType(row) {
            if (row.cmd == 'now') {
                return '快捷下单'
            } else if (row.cmd == 'third') {
                return '三键下单'
            } else {
                return '传统下单'
                
            }
        },
        loadSymbol() {
            sub({subcode: 'All', uid: localStorage.getItem('deviceid')}).then(res => {
            })
		},
        getContactlist() {
            contactlist({}).then(res => {
                if (res.code == 1) {
                    this.$store.commit('setContactList', res.data);
                } 
            })
        },
        createHash (hashLength) {
            if (!hashLength || typeof(Number(hashLength)) != 'number') {return;}
            let ar = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
            let hs = [];
            let hl = Number(hashLength);
            let al = ar.length;
            for (let i = 0; i < hl; i ++) {
                hs.push(ar[Math.floor(Math.random() * al)]);
            }
            return hs.join('');
        },
        sendHeartBean() {
            if (this.heartBean) {
                clearInterval(this.heartBean)
            }
            this.heartBean = setInterval( () => {
                this.$socket.send(JSON.stringify({ Cmd: 'heartbeat', uid: localStorage.getItem('deviceid') }));
            }, 5000)
        
        },
        contextmenu() {
            document.addEventListener('visibilitychange', () => {
                // 用户息屏、或者切到后台运行 （离开页面）
                if (document.visibilityState === 'hidden') {
                    this.$socket.close()
                    clearInterval(this.heartBean)
                    this.heartBean = null
                } else {
                    this.init(true)
                }
            }) //禁止鼠标右键菜单显示
        },
        init() {
            if (localStorage.getItem('deviceid') == 'null' || !localStorage.getItem('deviceid')) {
                this.hashid =  this.createHash(18)
                this.getDeviceid()
            } else {
                this.connect()
            }
        },
        connect() {
            this.conn(localStorage.getItem('deviceid'));
        },
        getDeviceid() {
            getdeviceid({hashid: this.hashid}).then(res => {
                if (res.code == 1) {
                    const { appid } = res.data
                    localStorage.setItem('deviceid', appid);
                    this.connect()
                } 
            })
        },
        // 获取 easy-mock 的模拟数据
        getData() {
            chicang(this.query).then(res => {
                this.tableData = res.data.list.map( item => {
                    const taDa = this.tableData.find(da => da.id == item.id)
                    if (taDa) {
                        item.checked = taDa.checked
                    } else {
                        item.checked = false
                    }
                    
                    return item
                });
                this.chicangnum = res.data.chicangnum
                this.pingcangnum = res.data.pingcangnum
                this.chicangyk = res.data.chicangyk
                this.total = res.data.total
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, "pageIndex", 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index) {
            // 二次确认删除
            this.$confirm("确定要删除吗？", "提示", {
                type: "warning"
            })
                .then(() => {
                    this.$message.success("删除成功");
                    this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange() {
            if (this.checkedAll) {
                this.tableData = this.tableData.map( item => {
                    item.checked = true
                    return item
                })
            } else {
                 this.tableData = this.tableData.map( item => {
                    item.checked = false
                    return item
                })
            }
            
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = "";
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + " ";
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, "pageIndex", val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.el-table td, .el-table th.is-leaf {
    border-bottom: 0;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
